var express = require('express');
var router = express.Router();
const Bizrelainst = require('../models/Bizrelainst');
var formidable = require('formidable');
var fs = require('fs');
const mineType = require("mime-types");
var tools = require('../utils/tools')

/**
 * @swagger
 * /cmdb/bizrelainsts:
 *   put:
 *     tags:
 *       - 业务关系实例管理
 *     summary: 更新业务关系实例
 *     description: 更新所有业务关系实例，目前只允许更新desc和属性值。关联关系、源实例、目标实例不允许更新
 *     responses:
 *       200:
 *         description: 返回标准结构
 */
router.put('/:id', async function (req, res, next) {
  var rInstance = await Bizrelainst.findById(req.params.id).populate('rela')
  if (!rInstance) {
    return tools.handleError(res, '关系不存在');
  }

  var attrs = []
  rInstance.rela.attrs.forEach(a => {
    attrs.push({ key: a.field, value: req.body.attrs[a.field] })
  })

  var { desc } = req.body
  var data = { desc, attrs }
  Bizrelainst.findByIdAndUpdate(req.params.id, { $set: data }, { new: true }, function (err, doc) {
    if (err) return tools.handleError(res, err);
    return res.json({ status: 'success', data: doc })
  });
});

module.exports = router;
